#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from google.appengine.ext import db
from appsina import AppEngineSina
from dservice import DService
from delladb import Delladb
from django.utils import simplejson

class SinaService:
    """Class to processing information from the sina users"""  
    def __init__( self ):
        """initializing the username and password"""
        self._tww=AppEngineSina('username','password')


    def checkQueries(self):
        results=self.getMessage()
        for content in results:
            match=self.praseMsg(content)
            if(match<>[]):
                dservice=DService(match[0])
                respons=dservice.parseCommand()
                if(respons<>[] and respons[0]<>'pass'):
                    for re in reversed(respons):
                        self.sentMessage(content['id'],re)
        if(results<>[]):
            self.updateSinaMsgId(results[0]['id'])

        results=self.getDM()
        for content in results:
            dservice=DService(content['text'])
            respons=dservice.parseCommand()
            if(respons<>[] and respons[0]<>'pass'):
                for re in respons:
                    self.sentDM(content['sender']['screen_name'],re)
        if(results<>[]):
            self.updateSinaDMId(results[0]['id'])
            
             
    def praseMsg(self,content):
        regex=r'^@idella (.*)'
        return re.findall(regex,content['text'].lower())

    
    def getMessage(self):
        since_id=self.getSinaMsgId()
        retry=3
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.mentions(since_id)
                if(statuscode==200):
                    break
            except:
                pass
        if(statuscode<>200):
            return []
        else:
            contents = simplejson.loads(self._tww.getContent())
            return contents

            
    def sentMessage(self,msg_id,msg):
        retry=4
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.comment(msg_id,msg)
                if(statuscode==200):
                    break
            except:
                pass


    def update(self,msg):
        retry=4
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.update(msg)
                if(statuscode==200):
                    break
            except:
                pass             



    def getDM(self):
        since_id=self.getSinaDMId()
        retry=3
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.getDMessage(since_id)
                if(statuscode==200):
                    break
            except:
                pass
        if(statuscode<>200):
            return []
        else:
            contents = simplejson.loads(self._tww.getContent())
            return contents


    def sentDM(self,user,msg):
        retry=4
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.sentDMessage(user,msg)
                if(statuscode==200):
                    break
            except:
                pass

          
    def getSinaMsgId(self):
        q=db.GqlQuery("SELECT * FROM Delladb")
        if(q.count()):
            return q[0].sinamsg
        else:
            return 12228721


    def updateSinaMsgId(self,msgid):
        q=db.GqlQuery("SELECT * FROM Delladb")
        for enty in q:
            enty.sinamsg=msgid
            db.put(enty)
        

    def getSinaDMId(self):
        q=db.GqlQuery("SELECT * FROM Delladb")
        if(q.count()):
            return q[0].sinadm
        else:
            return 1174929


    def updateSinaDMId(self,msgid):
        q=db.GqlQuery("SELECT * FROM Delladb")
        for enty in q:
            enty.sinadm=msgid
            db.put(enty)        




        
            
        
